package com.lagou.client;

import com.lagou.service.MyEncoder;
import com.lagou.service.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {

    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler ;

    private Long times;

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass, final String providerName, List<String> children,boolean flag,boolean flag2){

        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //（1）调用初始化netty客户端的方法
                if (flag||flag2){
                    for (String child : children) {
                        initClient(Integer.valueOf(child));
                        System.out.println("child"+child);
                    }
//          UserClientHandler userClientHandler = new UserClientHandler();
                }
                if(userClientHandler == null){
                    for (String child : children) {
                        initClient(Integer.valueOf(child));
                        System.out.println("child"+child);
                    }

                }
//                if (flag){
//          userClientHandler.notify();
//      }
                RpcRequest  request = new RpcRequest();
                String[] split = providerName.split("#");
                request.setServiceName(serviceClass);
                request.setArgs(args[0]);
                request.setMethodName(split[1]);
                // 设置参数
                userClientHandler.setPara(request);

                // 去服务端请求数据

                return executor.submit(userClientHandler).get();
            }
        });


    }




    //2.初始化netty客户端
    public static  void initClient(Integer port) throws InterruptedException {

        try {
            userClientHandler = new UserClientHandler();
            EventLoopGroup group = new NioEventLoopGroup();

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new MyEncoder());
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(userClientHandler);
                        }
                    });
//            userClientHandler.getTimes().put(port,0L);

            Map<Integer, Long> times = userClientHandler.getTimes();
            List<Map.Entry<Integer, Long>> list = new ArrayList<Map.Entry<Integer, Long>>(times.entrySet()); //转换为list
            list.sort(new Comparator<Map.Entry<Integer, Long>>() {
                @Override
                public int compare(Map.Entry<Integer, Long> o1, Map.Entry<Integer, Long> o2) {
                    return o2.getValue().compareTo(o1.getValue());
                }
            });

            if (list.size()>0){
                Map.Entry<Integer, Long> integerLongEntry = list.get(0);
                bootstrap.connect("127.0.0.1",integerLongEntry.getKey()).sync();
                userClientHandler.setPort(integerLongEntry.getKey());
            }else {
                bootstrap.connect("127.0.0.1",port).sync();
                userClientHandler.setPort(port);
            }
        } catch (Exception e){
            System.out.println(e);
//            userClientHandler.close();
        }
    }


}
